import axios, {
  AxiosError,
  InternalAxiosRequestConfig,
  AxiosResponse,
} from "axios";

// 创建axios实例
const request = axios.create({
  baseURL: "/api",
  timeout: 10000,
});

// 请求拦截器
request.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 从localStorage获取token
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    return response.data;
  },
  (error: AxiosError<any>) => {
    // 处理错误响应
    if (error.response) {
      const { status, data } = error.response;

      // 401 未授权，跳转到登录页
      if (status === 401) {
        localStorage.removeItem("token");
        window.location.href = "/login";
      }

      // 返回错误信息
      return Promise.reject(data?.detail || data?.message || "请求失败");
    }

    return Promise.reject(error.message || "网络错误");
  }
);

export default request;
